import java.io.IOException;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.logging.*;

/**
 * This is the medical record database that will hold all the medical records.
 * @author Matt Lee, Michael Zipp
 *
 */
public abstract class MedicalRecordDatabase implements Serializable{
	static AbstractCollection<MedicalRecord> recordsList;

	private static Logger medicalRecordDatabaseLog = 
		Logger.getLogger(MedicalRecordDatabase.class.getName());
	
	static{
		ConsoleHandler console = new ConsoleHandler();
		console.setLevel(Level.FINEST);
		console.setFormatter(new ThunderDragonHtmlFormatter());
		medicalRecordDatabaseLog.addHandler(console);
		medicalRecordDatabaseLog.setLevel(Level.ALL);
		
		try {
			FileHandler fh = new FileHandler("MedicalRecordDatabase.txt");
			fh.setFormatter(new ThunderDragonHtmlFormatter());
			medicalRecordDatabaseLog.addHandler(fh);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			medicalRecordDatabaseLog.severe("Failure: Security exception thrown" +
					" when trying to create a new handler " +
					"in MedicalRecordDatabase.java.");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			medicalRecordDatabaseLog.severe("Failure: I/O exception thrown" +
					" when trying to create a new handler " +
					"in MedicalRecordDatabase.java.");
			e.printStackTrace();
		}
		
	}

	/**
	 * Returns a specific patients medical record.
	 * @param patientUsername Username of the patient.
	 * @return Medical Record object of the patient.
	 */
	public static MedicalRecord searchPatientRecord(String patientUsername){
		medicalRecordDatabaseLog.finest("Searching for medical records...");
		for(MedicalRecord m : recordsList){
			if(m.patient.getUsername().equals(patientUsername)){ 
				return m;
			}
		}
		
		return null;
	}
	
	/**
	 * Adds a patient's medical record into the database.  
	 * This only does so if the patient
	 * is not found.
	 * @param patient
	 */
	public void addMedicalRecord(Patient patient){
		medicalRecordDatabaseLog.finest("Adding a new medical record...");
		if(!contains(patient)){
			recordsList.add(new MedicalRecord(patient));
		}
	}
	
	//Now we needs a remove method for the doctor or system admin...
	
	/**
	 * Checks to see if a specified patient's record is in the database.
	 * @param patient The patient we are searching for.
	 * @return the boolean designating whether or not they are in the database.
	 */
	public boolean contains(Patient patient){
		medicalRecordDatabaseLog.finest("Adding a new medical record...");
		for(MedicalRecord m: recordsList){
			if(m.patient.getUsername().equals(
					patient.getUsername())&&m.patient.getName().equals(
							patient.getName())){
				return true;
			}
		}
		return false;
	}
}